//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.szboanda.platform.common.component.pageoffice.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szboanda.platform.common.base.BaseService;
import com.szboanda.platform.common.component.pageoffice.adpter.IPageOfficeAdapter;
import com.szboanda.platform.common.component.pageoffice.dao.PageOfficeDAO;
import com.szboanda.platform.common.component.pageoffice.exceptions.PageOfficeException;
import com.szboanda.platform.common.component.pageoffice.helper.PageofficeHelper;
import com.szboanda.platform.common.component.pageoffice.service.IPageOfficeService;
import com.szboanda.platform.common.framext.mybatits.PlatformPageInfo;
import com.szboanda.platform.common.utils.*;
import com.szboanda.platform.file.service.IFileInfoService;
import com.szboanda.platform.file.service.IFileService;
import com.szboanda.platform.rms.user.mode.UserVO;
import com.zhuozhengsoft.pageoffice.FileSaver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageOfficeServiceImpl extends BaseService implements IPageOfficeService {
    @Autowired
    private PageOfficeDAO officeDao;
    @Autowired
    private IFileInfoService infoService;
    @Autowired
    private IFileService fileService;

    public PageOfficeServiceImpl() {
    }

    @Override
    public String updateFile(FileSaver fileSaver) throws PageOfficeException {
        IPageOfficeAdapter adpter = null;
        String adpterName = fileSaver.getFormField("beanName");
        String beanParams = fileSaver.getFormField("beanParams");
        String wjid = fileSaver.getFormField("wjid");
        boolean canSave = true;
        String ywsjid = fileSaver.getFormField("ywsjid");
        File tempFile = this.getTempFile(fileSaver, wjid);
        String tempSavePath = tempFile.getAbsolutePath();
        if (StringUtils.isNotEmpty(adpterName)) {
            adpter = (IPageOfficeAdapter)Toolkit.getSpringBean(adpterName);
            if (null != adpter) {
                canSave = adpter.beforeSave(ywsjid, tempSavePath, beanParams);
            }
        }

        if (!canSave) {
            return null;
        } else {
            if (StringUtils.isNotEmpty(wjid)) {
                String backRevisions = fileSaver.getFormField("BACK_REVISIONS");
                if (StringUtils.isNotEmpty(backRevisions)) {
                    this.backUpHistoryDoc(tempFile, wjid, backRevisions);
                }

                this.saveFileInfo(wjid, fileSaver.getFileSize());
                this.fileService.updateFile(tempFile, wjid);
            }

            if (null != adpter) {
                adpter.afterSave(ywsjid, tempSavePath, beanParams);
            }
            if(tempFile != null){
                boolean delete = tempFile.delete();
                if(delete){
                    System.out.println("删除成功");
                }
            }
            return wjid;
        }
    }

    private File getTempFile(FileSaver fileSaver, String wjid) {
        String dirPath = PageofficeHelper.getFileDiskPath("TEMP_FILE", this.getCurrUser().getYhid(), wjid);
        File dir = new File(dirPath);
        if (dir != null && !dir.exists()) {
            boolean mkdirs = dir.mkdirs();
            if(mkdirs){
               System.out.print("创建成功");
            }
        }

        String tempSavePath = dirPath + "/temp" + "MONGO_FILE";
        File tempFile = new File(tempSavePath);
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException var9) {
                String msg = String.format("创建临时文件失败tempSavePath=%s", tempSavePath);
                LoggerUtil.error(this.getClass(), msg, var9);
                throw new PageOfficeException(msg, var9);
            }
        }

        fileSaver.saveToFile(tempSavePath);
        return tempFile;
    }

    private void saveFileInfo(String wjid, int fileSize) {
        try {
            Date curDate = new Date();
            UserVO user = this.getCurrUser();
            Map<String, Object> objFile = new HashMap();
            objFile.put("SCRID", user.getYhid());
            objFile.put("SCR", user.getName());
            objFile.put("WJDX", (double)fileSize * 1.0D / 1024.0D);
            objFile.put("SCSJ", curDate);
            objFile.put("WJID", wjid);
            this.infoService.updateFileInfo(objFile);
        } catch (Exception var6) {
            LoggerUtil.error(this.getClass(), "pageoffice更新文本信息异常", var6);
            throw new PageOfficeException("pageoffice更新文本信息异常", var6);
        }
    }

    private void backUpHistoryDoc(File tempFile, String wjid, String backRevisions) {
        Map<String, Object> sourceFileInfo = this.fileService.getFileInfo(wjid);
        Map<String, Object> historyInfo = new HashMap();
        Map historyFileInfo = sourceFileInfo;

        String msg;
        try {
            this.createBaseInfo(historyInfo);
            String historyId = Toolkit.getUUID();
            historyInfo.put("XH", historyId);
            historyInfo.put("WDBH", wjid);
            msg = MapUtils.getString(sourceFileInfo, "WJMC");
            historyInfo.put("WDMC", msg.substring(0, msg.length() > 25 ? 25 : msg.length()));
            historyInfo.put("XDNR", backRevisions);
            historyInfo.put("BBH", "0");
            historyInfo.put("BCMS", "起草");
            historyInfo.put("BCLJ", historyId);
            historyInfo.put("BZ", "");
            UserVO user = this.getCurrUser();
            historyInfo.put("BCYH", user.getYhid());
            Date curDate = new Date();
            historyInfo.put("BCSJ", curDate);
            if (null == historyInfo.get("ORGID")) {
                historyInfo.put("ORGID", "");
            }

            this.officeDao.addFileHistory(historyInfo);
            this.createBaseInfo(historyFileInfo);
            historyFileInfo.put("WJID", historyId);
            historyFileInfo.put("YWSJID", historyId);
            historyFileInfo.put("LXDM", "PAGEOFFICE");
            historyFileInfo.put("ZLXDM", "PAGEOFFICE_HISTORY");
            this.fileService.addFile(tempFile, historyFileInfo);
        } catch (Exception var11) {
            msg = String.format("pageoffice历史版本备份异常%n historyInfo=%s%nhistoryFileInfo=%s", historyInfo.toString(), sourceFileInfo);
            LoggerUtil.error(this.getClass(), msg, var11);
            throw new PageOfficeException(msg, var11);
        }
    }

    @Override
    public Map<String, Object> getHistoryFileById(String fileId) throws PageOfficeException {
        try {
            Map<String, Object> fileInfo = null;
            Map<String, Object> conditions = new HashMap();
            conditions.put("XH", fileId);
            List<Map<String, Object>> lstFileInfo = this.officeDao.getFileHistoryList(conditions);
            if (!CollectionUtils.isEmpty(lstFileInfo)) {
                fileInfo = (Map)lstFileInfo.get(0);
                File file = new File(MapUtils.getString(fileInfo, "BCLJ"));
                fileInfo.put("file", file);
            }

            return fileInfo;
        } catch (Exception var6) {
            LoggerUtil.error(this.getClass(), "pageoffice历史版本备份异常", var6);
            throw new PageOfficeException("pageoffice历史版本备份异常", var6);
        }
    }

    public Map<String, Object> getFileByUserId(String userId) throws PageOfficeException {
        try {
            Map<String, Object> modelInfo = new HashMap();
            modelInfo.put("ZLXDM", "signature");
            modelInfo.put("YWSJID", userId);
            Map<String, Object> fileInfo = null;
            int pageSize = 1;
            int pageNum = 1;
            PageInfo<Map<String, Object>> pageInfo = this.infoService.queryFileInfos(pageNum, pageSize, modelInfo);
            if (null != pageInfo) {
                List<Map<String, Object>> lstFile = pageInfo.getList();
                if (CollectionUtils.isNotEmpty(lstFile)) {
                    fileInfo = (Map)lstFile.get(0);
                }
            }

            return fileInfo;
        } catch (Exception var8) {
            LoggerUtil.error(this.getClass(), "pageoffice历史版本备份异常userId=" + userId, var8);
            throw new PageOfficeException("pageoffice历史版本备份异常", var8);
        }
    }

    public PageInfo<Map<String, Object>> getFileHistoryList(int pageNum, int pageSize, Map<String, Object> condition) throws PageOfficeException {
        try {
            SQLUtils.fillLike(condition, "XDNR", true, true);
            PageHelper.startPage(pageNum, pageSize);
            String beginTime = MapUtils.getString(condition, "beginTime");
            if (StringUtils.isNotEmpty(beginTime)) {
                condition.put("beginTime", DateUtils.parseDateStrictly(beginTime + " 00:00:00", new String[]{"yyyy-MM-dd HH:mm:ss"}));
            } else {
                condition.put("beginTime", (Object)null);
            }

            String endTime = MapUtils.getString(condition, "endTime");
            if (StringUtils.isNotEmpty(endTime)) {
                condition.put("endTime", DateUtils.addDays(DateUtils.parseDateStrictly(endTime + " 00:00:00", new String[]{"yyyy-MM-dd HH:mm:ss"}), 1));
            } else {
                condition.put("endTime", (Object)null);
            }

            List<Map<String, Object>> lstFileInfo = this.officeDao.getFileHistoryList(condition);
            PageInfo<Map<String, Object>> objPageInfo = new PlatformPageInfo(lstFileInfo, "yyyy-MM-dd HH:mm:ss");
            return objPageInfo;
        } catch (Exception var8) {
            LoggerUtil.error(this.getClass(), "获取文档历史版本信息出错condition=" + condition, var8);
            throw new PageOfficeException("获取文档历史版本信息出错", var8);
        }
    }

    public Map<String, Object> getOfficeFileInfo(String templateId, String ywsjId, String fileName, UserVO user) throws PageOfficeException {
        Map<String, Object> tempFile = this.fileService.getFileInfo(templateId);
        if (null != tempFile) {
            try {
                //  没有看懂， 为什么每次打开都先保存一份新的文件，是为了留第一次上传的文件吗？  暂时注释：袁云飞 2019-10-23
             /*   String wjId = ywsjId + "_" + templateId;
                if (wjId.length() > 70) {
                    wjId = wjId.substring(0, 70);
                }

                Map<String, Object> objFile = this.fileService.getFileInfo(wjId);
                if (null == objFile) {
                    objFile = this.getFileInfo(wjId, fileName, ywsjId, tempFile, user);
                    File templateFile = this.fileService.downloadFile(templateId);
                    this.fileService.addFile(templateFile, objFile);
                }*/

                return tempFile;
            } catch (Exception var9) {
                String errInfo = "根据模版文件生成文档异常(templateId,ywsjId,fileName)=(" + templateId + "," + ywsjId + "," + fileName + ")";
                LoggerUtil.error(this.getClass(), errInfo, var9);
                throw new PageOfficeException(errInfo, var9);
            }
        } else {
            LoggerUtil.error(this.getClass(), "模版文件不存在!");
            throw new PageOfficeException("模版文件不存在!");
        }
    }

    private Map<String, Object> getFileInfo(String wjId, String fileName, String ywsjId, Map<String, Object> tempFile, UserVO user) {
        if (user == null) {
            user = new UserVO();
        }

        if (StringUtils.isEmpty(fileName)) {
            fileName = MapUtils.getString(tempFile, "WJMC");
        } else if (fileName.indexOf(46) == -1) {
            fileName = fileName + '.' + MapUtils.getString(tempFile, "WJLX");
        }

        String lxdm = MapUtils.getString(tempFile, "LXDM");
        String zlxdm = MapUtils.getString(tempFile, "ZLXDM");
        Map<String, Object> objFile = new HashMap();
        Date curDate = new Date();
        String fileType = MapUtils.getString(tempFile, "WJLX");
        objFile.put("WJID", wjId);
        objFile.put("LXDM", lxdm);
        objFile.put("ZLXDM", zlxdm);
        objFile.put("WJMC", fileName);
        objFile.put("WJLX", fileType);
        objFile.put("WJDX", tempFile.get("WJDX"));
        objFile.put("PXH", 1);
        objFile.put("SCRID", user.getYhid());
        objFile.put("SCR", user.getYhmc());
        objFile.put("SCSJ", curDate);
        objFile.put("XZCS", 0);
        objFile.put("SFSC", 2);
        objFile.put("YWSJID", ywsjId);
        return objFile;
    }
}
